package com.dc.web.controller;


import com.dc.constant.MessageConstant;
import com.dc.dao.ShipDao;
import com.dc.dao.ShipRepairDao;
import com.dc.dao.WorkflowMachinePipeDao;
import com.dc.entity.ShipEntity;
import com.dc.entity.ShipRepairEntity;
import com.dc.entity.WorkflowMachinePipeEntity;
import com.dc.entity.WorkflowShipCutEntity;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.WorkflowListBody;
import com.dc.service.CalibrationService;
import com.dc.service.dto.CalibrationMachinePipeDto;
import com.dc.service.dto.CalibrationShipCutDto;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;

@Api(tags = "3-单船工序-机电管子焊接")
@RequestMapping("/api/workflow_machine_pipe")
@RestController
public class WorkflowMachinePipeController {

    @Resource
    WorkflowMachinePipeDao workflowMachinePipeDao;

    @Resource
    ShipRepairDao shipRepairDao;

    @Resource
    ShipDao shipDao;

    @Resource
    CalibrationService calibrationService;

    @GetMapping("/list")
    public AjaxResult list(WorkflowListBody body) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Long repairId = body.getRepairId();     // 维修工单id

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(repairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        Page<WorkflowMachinePipeEntity> resultList = workflowMachinePipeDao.findByShipRepairEntity(shipRepairEntity, pageRequest);

        CalibrationMachinePipeDto calibrationMachinePipeDto = calibrationService.calcMachinePipe();

        resultList.getContent().forEach(t -> {
            dynamicCalc(t, shipEntity, shipRepairEntity, calibrationMachinePipeDto);
        });

        return AjaxResult.success(resultList);
    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<WorkflowMachinePipeEntity> optional = workflowMachinePipeDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowMachinePipeEntity machinePipeEntity = optional.get();

        ShipRepairEntity shipRepairEntity = machinePipeEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);

        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        CalibrationMachinePipeDto calibrationMachinePipeDto = calibrationService.calcMachinePipe();

        dynamicCalc(machinePipeEntity, shipEntity, shipRepairEntity, calibrationMachinePipeDto);

        return AjaxResult.success(machinePipeEntity);
    }

    @PostMapping()
    public AjaxResult add(@RequestHeader HttpHeaders httpHeaders, @RequestBody WorkflowMachinePipeEntity entity) {

        entity.setId(null);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);
        entity.setSubmitTime(new Date());

        WorkflowMachinePipeEntity save = workflowMachinePipeDao.save(entity);

        CalibrationMachinePipeDto calibrationMachinePipeDto = calibrationService.calcMachinePipe();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationMachinePipeDto);

        return AjaxResult.success(save);
    }

    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody WorkflowMachinePipeEntity entity) {

        entity.setId(id);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);
        entity.setSubmitTime(new Date());

        WorkflowMachinePipeEntity save = workflowMachinePipeDao.save(entity);

        CalibrationMachinePipeDto calibrationMachinePipeDto = calibrationService.calcMachinePipe();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationMachinePipeDto);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        workflowMachinePipeDao.deleteById(id);

        return AjaxResult.success();
    }

    /**
     * 计算动态值
     * @param entity
     * @param shipEntity
     * @param shipRepairEntity
     *    shipName;        // 船体名称
     *    reporter;        // 填报人
     *    flLength;          // 法兰长度     // diam * flNum * pi
     *    wgLength;          // 弯管长度     // diam * ( zgNum + wgNum + tgNum) * pi
     *    wghfLength;        // 弯管焊缝长度     // wgLength / 1000
     *    wgPowerByUnit;     // 弯管单位耗电量标定值
     *    wgPower;           // 弯管耗电量   wgPowerByUnit * wghfLength
     *    flhfLength;        // 法兰焊缝长度     // flLength / 1000
     *    flPowerByUnit;     // 法兰单位耗电量标定值
     *    flPower;           // 法兰耗电量  flPowerByUnit * flhfLength
     *
     */
    // 弯头管子焊接单位用电量标定值
    // 法兰管子焊接单位用电量标定值（kwh/m)
    public static WorkflowMachinePipeEntity dynamicCalc(
            WorkflowMachinePipeEntity entity,
            ShipEntity shipEntity,
            ShipRepairEntity shipRepairEntity,
            CalibrationMachinePipeDto calibrationShipCutDto) {

        entity.setShipName(shipEntity.getName());
        entity.setReporter(shipRepairEntity.getUpdater());
        entity.setShipRepairId(shipRepairEntity.getId());

        try {
            Double flLength = entity.getDiam() * entity.getFlNum() * Math.PI;
            entity.setFlLength(flLength);
        } catch (Exception e) {
            entity.setFlLength(0.);
        }

        try {
            Double wgLength = entity.getDiam() * ( entity.getZgNum() + entity.getWgNum() + entity.getTgNum()) * Math.PI;
            entity.setWgLength(wgLength);
        } catch (Exception e) {
            entity.setWgLength(0.);
        }

        try {
            Double wghfLength = entity.getWgLength() / 1000;
            entity.setWghfLength(wghfLength);
        } catch (Exception e) {
            entity.setWghfLength(0.0);
        }

        try {
            Double wgPowerByUnit = calibrationShipCutDto.getWantouYahuPowerByUnit();
            entity.setWgPowerByUnit(wgPowerByUnit);
        } catch (Exception e) {
            entity.setWgPowerByUnit(0.);
        }

        try {
            Double wgPower = entity.getWgPowerByUnit() * entity.getWghfLength();
            entity.setWgPower(wgPower);
        } catch (Exception e) {
            entity.setWgPower(0.);
        }

        try {
            Double flhfLength = entity.getFlLength() / 1000;
            entity.setFlhfLength(flhfLength);
        } catch (Exception e) {
            entity.setFlhfLength(0.);
        }

        try {
            Double flPowerByUnit = calibrationShipCutDto.getFalanPowerByUnit();
            entity.setFlPowerByUnit(flPowerByUnit);
        } catch (Exception e) {
            entity.setFlPowerByUnit(0.);
        }

        try {
            Double flPower = entity.getFlPowerByUnit() * entity.getFlhfLength();
            entity.setFlPower(flPower);
        } catch (Exception e) {
            entity.setFlPower(0.);
        }

        return entity;
    }
}
